#include <PhysicsObject.h>
#include <Transform.h>
#include <GraphicData.h>
#include <Physics.h>

	/*
	b2BodyDef bodyDef;
	bodyDef.type = b2_dynamicBody;
	bodyDef.position.Set(0,5);
	b2Body* body = world->CreateBody(&bodyDef);
	b2PolygonShape dynamicBox;
	dynamicBox.SetAsBox(2,2);
	b2FixtureDef fixtureDef;
	fixtureDef.shape = &dynamicBox;
	fixtureDef.density = 1;
	fixtureDef.friction = 0.3f;
	body->CreateFixture(&fixtureDef);
	btest = body;
	*/

PhysicsObject::PhysicsObject(BaseObject* b, Transform* t, std::vector<vec2> boundingBox, b2BodyType bodytype)
:transform(t)
,bodyFixture(0)
{
	if( !t )
		throw 0;
	
	if( boundingBox.empty() )
		throw 0;

	bodyDef.type = bodytype;
	bodyDef.position.Set( transform->loc.x, transform->loc.y );
	body = External::physics->world->CreateBody(&bodyDef);
	body->SetTransform( transform->loc, transform->angle );
	body->SetUserData( b );

	bbox = boundingBox;

	CreateBoundingBox(t->scale);
}

PhysicsObject::~PhysicsObject()
{
	//body->DestroyFixture( bodyFixture ); //TODO: maybe use this?
	body->SetTransform( b2Vec2(-10000,-10000),0 );
	External::physics->world->DestroyBody(body);
}

void PhysicsObject::CreateBoundingBox(float scale)
{
	if(bodyFixture)
		body->DestroyFixture( bodyFixture );

	for( unsigned i = 0; i < bbox.size(); ++i)
	{
		bbox[i] *= scale;
	}
	shape.Set( &bbox.front(), bbox.size() );
	fixtureDef.shape = &shape;
	fixtureDef.density = 1;
	fixtureDef.friction = 0.3f;
	bodyFixture = body->CreateFixture(&fixtureDef);
}